<template>
  <div class="wrap">
    <div class="tabButton">
      <span class="chatButton" @click="$router.replace('/')">{{$t('chatTab')}}</span>
      <span class="paintingButton">{{$t('paintingTab')}}</span>
    </div>
    <div class="chat-container" :style="{ width: `calc(100vw - 20px)` }">
      <el-main class="chat-main">
        <div class="chat-messages" ref="chatMessages">
          <div v-for="(message, index) in messages" :key="index"
            :class="{ 'chat-message-left': message.role === 'assistant', 'chat-message-right': message.role === 'user' }">
            <div class="chat-avatar">
              <img v-show="message.role === 'assistant'" src="../assets/chatGPT.png" alt="">
            </div>
            <div class="chat-content">
              <span v-html="md.render(message.content)" class="chat-message-text"></span>
              <span v-show="message.role === 'assistant' && !inAnswer && message.errorMsg === true"
                class="regenerate">
                  <el-icon class="Refresh" size="24">
                    <WarningFilled />
                  </el-icon>
              </span>
            </div>
            <div class="chat-avatar">
              <img v-show="message.role === 'user'" src="../assets/avatar3.jpg" alt="">
            </div>
          </div>
          <div class="chat-message-left" v-show="loadingAnimation">
            <div class="chat-avatar">
              <img src="../assets/chatGPT.png" alt="">
            </div>
            <div class="chat-content">
              <span class="chat-message-text" style="height: 50px;line-height:50px">{{$t('paint.inPainting')}} <el-icon class="is-loading">
                  <Loading />
                </el-icon>
              </span>
            </div>
          </div>
          <div v-show="inAnswer" class="suspend" @click="suspend"><el-button type="danger" round>{{$t('paint.stopAnswering')}}</el-button></div>
        </div>
      </el-main>
      <!-- <el-input v-model="inputText"></el-input><el-button type="primarry" @click="sendMessage('$event')">发送</el-button>  -->
      <!-- 语音不行时用input测试 --> 
      <el-icon class="voiceInput" @click="startRecognition" v-show="!Distinguish">
        <Microphone />
      </el-icon>
      <el-icon class="voiceInput  is-loading" @click="endRecognition" v-show="Distinguish">
        <Loading />
      </el-icon>
      <!-- <Waveform ref="Waveform"/> -->
    </div>
    <pictureDialog ref="pictureDialog" :name="name" :loading="loading" :pictureList="pictureList" v-model="dialogVisible" :Action="Action" @closeDialog="closeDialog" @submit="submit"></pictureDialog>
  </div>
</template>

<script>
import MarkdownIt from 'markdown-it'
import Hljs from "highlight.js";  //高亮代码
import { parseTime, getuuid, speakText } from '../utils/index'
import { getgptimage } from '../api/connrequest'
// import Waveform from './components/Waveform.vue'; //声波效果
import pictureDialog from './components/pictureDialog.vue'
import "../assets/_highlight.js@11.8.0@highlight.js/styles/monokai-sublime.css";

export default {
  components: {
    // Waveform,
    pictureDialog
  },
  data() {
    return {
      name: '',
      dialogVisible: false,
      loading: false,
      pictureList: [],
      inputText: '',
      loading: false,
      inAnswer: false,
      isSpeak: true,
      Distinguish: false,
      recognition: null,
      loadingAnimation: false,
      messages: [],
      controller: new AbortController(), // 创建AbortController实例
      apiMessage: [
        { role: 'system', content: `you are a helpful assistant` }
      ],
      htmlStr: '',
      md: new MarkdownIt({
        html: true,
        typographer: true,
        highlight: function (str, lang) {
          if (lang && Hljs.getLanguage(lang)) {
            try {
              let idname = `name${getuuid()}`
              return `<pre class="hljs"><div class="code-block-header"><span class="code-block-header__lang">${lang}</span></div><code id='${idname}'>` +
                Hljs.highlight(lang, str, true).value +
                '</code></pre>';
            } catch (__) { }
          }
          return '';
        }
      })
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    if (this.messages.length === 0) {
      this.messages.push(
        { created: parseTime(Date.now()), role: 'assistant', content: this.$t('paint.welcome'), Question: 'Hello' }
      )
    }
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    // 结束朗读
    // speechSynthesis.cancel()
    // 添加键盘事件监听器
    window.addEventListener('keydown', this.handleKeyDown);
  },
  beforeDestroy() {
    if (this.recognition) {
      this.recognition.stop();  // 清理识别器
    }
    window.removeEventListener('keydown', this.handleKeyDown);
  },
  methods: {
    suspend() {
      this.controller.abort();
      this.inAnswer = false
      this.loadingAnimation = false
    },
    async sendMessage(event) {
      if (this.inAnswer) {
        return
      }
      if (this.inputText === '') {
        return
      }
      if (event.shiftKey) {
        this.inputText += '\n'
      } else {
        // 执行发送信息的操作
        if (this.loading === true) {
          return false
        }
        let prompt = ''
        prompt = this.inputText
        const userMessage = { content: prompt, role: 'user', created: parseTime(Date.parse(new Date())) };
        this.messages.push(userMessage);
        this.inputText = ''
        // 发送信息后返回div底部
        this.$nextTick(() => {
          this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;
        })
        // 向后端发送请求，获取机器人的回复 GetGPTreply
        this.GetGPTreply(prompt)
      }
    },
    async GetGPTreply(prompt) {
      this.loadingAnimation = true
      this.inAnswer = true
      let arr = JSON.parse(JSON.stringify(this.messages));
      arr.push({ role: 'user', content: prompt });
      arr = arr.map(item => {
        delete item.created;
        delete item.Question
        return item;
      });
      arr = arr.slice(-10)
      const gptdata = {
        prompt: prompt,
        n: 1,
        size: "1024x1024"
      }
      // 取消之前的请求
      if (this.controller) {
        this.controller.abort();
      }
      this.controller = new AbortController();
      const res = await getgptimage(gptdata)
      console.log(res);
      if(!res.Data.data){
        // 使用正则表达式来提取Msg的内容
        const msgContent = res.Data.Status.Msg2Client;
        const botMessage = {
          role: 'assistant',
          content: `${msgContent}`,
          created: parseTime(Date.parse(new Date())),
          errorMsg: true
        };
        // 将机器人消息添加到聊天记录中
        this.messages.push(botMessage);
        this.inAnswer = false
        this.loadingAnimation = false
      }else{
        const botMessage = {
          role: 'assistant',
          content: `${this.$t('paint.Completed')}`,
          created: parseTime(Date.parse(new Date())),
        };
        // 将机器人消息添加到聊天记录中
        this.messages.push(botMessage);
        this.pictureList =  res.Data.data
        this.dialogVisible = true
        this.inAnswer = false
        this.loadingAnimation = false
      }
    },
    obtainJSON(value) {
      // 通过正则表达式匹配所有的 'data' 对象
      let inputString = value;
      // 以换行符分割每个 'data' 对象
      let dataArray = inputString.split('\n\n') || [];
      // 遍历每个 'data' 对象并存储在数组中
      dataArray = dataArray.filter(item => item.trim() !== '');
      let jsonDataArray = dataArray.map(data => {
        try {
          return JSON.parse(data.substring('data: '.length));
        } catch (error) {
          console.error('JSON 解析失败:', error.message);
          return null;
        }
      });
      // 过滤掉解析失败的对象
      jsonDataArray = jsonDataArray.filter(jsonData => jsonData !== null);
      // 提取 'answer' 属性
      let answers = jsonDataArray.map(jsonData => jsonData.answer);
      return answers.join('');
    },
    speak(value) {
      this.isSpeak = false
      // 获取选中的文本
      const selection = window.getSelection().toString();
      speakText(selection || value)
    },
    Stopspeak() {
      this.isSpeak = true
      // speechSynthesis.cancel()
    },
    initRecognition() {
      // 检查浏览器是否支持 Web Speech API
      if (!('webkitSpeechRecognition' in window)) {
        alert(`${this.$t('speechError.sorry')}`);
        return;
      }
      // 创建识别对象
      const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
      this.recognition = new SpeechRecognition();
      this.recognition.continuous = false; // 设置为 false 以进行一次语音识别
      this.recognition.interimResults = false; // 不需要中间结果
      // this.recognition.lang = 'ja-JP';
      // 处理开始
      this.recognition.onstart = (event) => {
      };
      // 处理结束
      this.recognition.onend = (event) => {
        // this.recognition.start()
        this.Distinguish = false
      };
      // 处理结果
      this.recognition.onresult = (event) => { 
        // this.$refs.Waveform.stopRecording()
        const transcript = event.results[event.resultIndex][0].transcript.trim();
        this.Distinguish = false
        this.inputText = transcript; // 获取转化后的文本
        this.sendMessage('$event')
        this.endRecognition()
      };
      // 处理错误
      this.recognition.onerror = (event) => {
        // this.$refs.Waveform.stopRecording()
        this.Distinguish = false
        let content = ''
        switch (event.error) {
          case 'no-speech':
            content = `${this.$t('speechError.noSpeech')}`
          break;
          case 'network':
            content = `${this.$t('speechError.network')}`
          break;
          case 'not-allowed':
            content = `${this.$t('speechError.notAllowed')}`
          break;
          case 'audio-capture':
            content = `${this.$t('speechError.audioCapture')}`
          break;
          case 'language-not-supported':
            content = `${this.$t('speechError.languageNotSupported')}`
          break;
          case 'service-not-allowed':
            content = `${this.$t('speechError.serviceNotAllowed')}`
          break;
          case 'no-speech-input':
            content = `${this.$t('speechError.noSpeechInput')}`
          break;
          default:
            content = `${this.$t('speechError.error')}`
            break;
        }
        this.messages.push(
          { created: parseTime(Date.now()), role: 'assistant', content, Question: 'Hello' }
        )
        this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;
        console.error("识别错误:", event);
      };
    },
    // 开始语音识别
    startRecognition() {
      if (!this.recognition) {
        this.initRecognition();  // 初始化识别器
      }
      this.recognition.start();
      this.Distinguish = true
      // this.$refs.Waveform.startRecording()
    },
    // 结束语音试别
    endRecognition() {
      if (this.recognition) {
        this.Distinguish = false
        this.recognition.stop();
      }
      // this.$refs.Waveform.stopRecording()
    },
    // 监听回车键
    handleKeyDown(event) {
      // alert(event.key)
      if (event.key === 'Enter') {
        event.preventDefault(); // 阻止默认行为
        if(this.dialogVisible){
          this.dialogVisible = false
        }else{
          this.toggleRecognition(); // 切换识别状态
        }
      }
      if (event.key === 'ArrowLeft') {
        this.$router.replace('/')
      }
    },
    // 切换识别状态
    toggleRecognition() {
      if (this.Distinguish) {
        this.endRecognition();
      } else {
        this.startRecognition();
      }
    },
  },
};
</script>

<style scoped lang="scss">
.wrap {
  position: relative;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  display: flex;
  height: calc(100vh - 20px);
  background: #181c25;
  padding: 10px;

  .ArrowLeftBold {
    position: absolute;
    font-size: 20px;
    top: 45%;
    left: 270px;
    border-radius: 5px 0px 0px 5px;
    background: #459ffc;
    height: 30px;
    z-index: 100;
    cursor: pointer;

    svg {
      color: #fff;
    }
  }

  .tabButton{
    position: absolute;
    top: 20px;
    right: 20px;
    display: flex;
    background: #2a3346;
    color: #99a5be;
    border-radius: 10px;
    z-index: 100;
    cursor: pointer;
    .chatButton{
      padding: 10px;
      border-radius: 10px;
    }
    .paintingButton{
      background: #15ADB6;
      color: #fff;
      padding: 10px;
      border-radius: 10px;
    }
  }
}

.chat-container {
  position: relative;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.chat-header {
  background-color: #409eff;
  color: white;
  text-align: center;
}


::-webkit-scrollbar {
  width: 5px;
}

/* 修改滚动条的轨道颜色 */
::-webkit-scrollbar-track {
  width: 5px;
  background-color: #f1f1f1;
}

/* 修改滚动条的滑块颜色 */
::-webkit-scrollbar-thumb {
  background-color: #ccc;
}

/* 修改滚动条的滑块形状 */
::-webkit-scrollbar-thumb:hover {
  background-color: #555;
}

/* 修改滚动条的角落 */
::-webkit-scrollbar-corner {
  background-color: #f1f1f1;
}

.sendInput {
  position: relative;
  padding: 20px;
  max-width: 80%;
  margin: 30px auto 0;

  .sendButton {
    position: absolute;
    bottom: 30px;
    right: 40px;
  }

  .cosplay {
    color: #b8b8b8;
    position: absolute;
    bottom: 8px;
    right: 50px;
    cursor: pointer;
  }

  .changeModel {
    position: absolute;
    left: 20px;
    top: -20px;
    color: #b8b8b8;
    position: absolute;
    bottom: 8px;
    right: 80px;
    cursor: pointer;
  }
}

.voiceInput {
  font-size: 50px;
  color: #009DFF;
  position: absolute;
  bottom: 40px;
  right: calc(50% - 20px);
  z-index: 1000;
  cursor: pointer;
}

.chat-main {
  flex: 1;
  padding: 20px;
  background: #202735;
}

.chat-messages {
  height: calc(100vh - 180px);
  overflow-y: auto;
  font-size: 1rem;
  line-height: 25px;
  display: flex;
  flex-direction: column;

  .seeMore {
    text-align: center;
    cursor: pointer;
    color: #409EFF;
  }

  .regenerate {
    cursor: pointer;
    position: absolute;
    right: 10px;
    bottom: 8px;

    .el-icon svg {
      font-size: 28px !important;
      color: red;
    }
  }

}

.suspend {
  position: relative;
  z-index: 1000;
  text-align: center !important;
  cursor: pointer;
  color: #F56C6C;
}

.chat-avatar {
  padding-top: 10px;

  img {
    width: 35px;
    border-radius: 50%;
  }
}

.chat-content {
  position: relative;
  display: flex;
  flex-direction: column;
}

pre {
  // background-color: #f4f6f8;
  padding: 10px;
  border-radius: 10px;
}

.chat-message-left {
  width: 50vw;
  display: flex;
  border-radius: 5px;
  margin: 10px 0;
  align-self: flex-start;

  .chat-message-text {
    width: 100%;
    overflow-y: auto;
    width: 50vw;
    align-self: flex-start;
    margin-left: 10px;
    border-radius: 5px;
    padding: 0 10px;
    color: #FEFEFF;
    background-color: #283142;
    word-wrap: break-word;
  }

  .chat-time {
    align-self: flex-start;
    font-size: 12px;
    color: #ccc;
    padding-left: 10px;
  }

  .copy {
    color: #409EFF;
    cursor: pointer;
  }
}

.chat-message-right {
  display: flex;
  max-width: 80%;
  border-radius: 5px;
  margin: 10px 0;
  align-self: flex-end;

  .chat-message-text {
    color: #fff;
    align-self: flex-end;
    margin-right: 10px;
    border-radius: 5px;
    padding: 0 10px;
    background-color: #009dff;
  }

  .chat-time {
    font-size: 12px;
    color: #ccc;
    padding-right: 10px;
    align-self: flex-end;
  }
}


.chat-input {
  flex: 1;
  margin-right: 10px;
}

.chat-footer {
  position: fixed;
  bottom: 40px;
  width: 80%;
  left: 10%;
  display: flex;
  align-items: center;
}

.dialog-footer {
  display: inline-block;
  display: flex;
  align-items: right;
  justify-content: flex-end;
  padding-bottom: 40px;
  padding-right: 20px;
}

.day7::before {
  // content: "最近7天：" !important;
  color: #dddddd;
}

:focus {
  outline: 0;
}
</style>

<style>
/** 列表样式 **/

code {
  font-size: 1rem;
  font-family: '微软雅黑' !important;
}

html {
  font-size: 100%;
  /* 默认基准字体大小 */
}

body {
  font-size: 1rem;
  /* 16px */
}

@media (min-width: 1200px) {

  /* 针对大屏幕或投影仪 */
  .chat-messages {
    font-size: 2rem;
    /* 增大字体大小 */
  }
}

.markdown ol {
  list-style-type: decimal;
  padding-left: 40px;
}

.markdown ul {
  list-style-type: disc;
  padding-left: 40px;
}

.code-block-header {
  width: 100%;
  background: #000 !important;
  display: flex;
  justify-content: space-between;
  color: #dddddd;
}

.code-block-header__lang,
.code-block-header__copy {
  padding: 5px;
  cursor: pointer;
}

/* .demo-tabs{ */
.el-tabs__item {
  font-size: 14px;
  padding: 0 10px;
}

.el-tabs__nav:first-child::before {
  font-family: "Microsoft YaHei", Arial, sans-serif;
  font-size: 14px;
  padding-top: 10px;
  padding-left: 10px;
  padding-right: 10px;
  content: "模板：";
  color: #a3a3a3;
}

/* } */
</style>